import { useEffect, useState, forwardRef, useRef } from 'react';
import { App } from 'antd';
import loadable from '@loadable/component';

import { isRegMobile, customSetTimeout } from '@/utils';
import { sendSms } from '@/service/base';

import styles from './index.module.scss';

export default forwardRef((props, ref) => {
    const timeLimit = 60;
    const initState = () => ({
        submitting: false,
        success: false,
        time: timeLimit,
        sending: false,
        counting: false,
    });
    const [state, setState] = useState(initState);
    const loopHandler = useRef(null);
    const { message } = App.useApp();
    const { phone, type } = props;

    // 发送验证码
    const sendCaptcha = (captcha={}) => {

        sendSms({mobile: phone, state: type, ...captcha}).then(([response, err]) => {
            setState(o => ({...o, sending: false}));

            if(OK_CODE === response?.code) {
                setState(o => ({...o, counting: true}));
                message.success(`验证码已发送，注意查收`);

                let timeLoopNumber = timeLimit;

                loopHandler.current = customSetTimeout((v) => {
                    if(timeLoopNumber <= 0) {
                        setState(o => ({...o, time: timeLimit, counting: false}));
                        loopHandler.current();
                    }else{
                        timeLoopNumber--;
                        setState(o => ({...o, time: timeLoopNumber}));
                    }
                }, 1000);
            }else{
                setState(o => ({...o, counting: false}));
                message.warning(response?.msg || err?.msg || response?.message || err?.message);
            }
        }).catch(e => {
            setState(o => ({...o, sending: false, counting: false}));
            message.error(e?.message || e?.msg);
        });
    }

    // 点击发送验证码
    const toSendCaptcha = () => {
        message.destroy();
        const { sending, counting } = state;
        if(sending || counting) return;
        if(!phone) return message.warning('请输入手机号');
        if(!isRegMobile(phone)) return message.warning('请输入正确的手机号');

        setState(o => ({...o, sending: true})); // 如果放到sendCaptcha，state的改变会导致组件重新渲染
        sendCaptcha();
    };

    return (
        <>
            <div
                className={`${styles['container']} ${state.sending ? styles['sending'] : (state.counting ? styles['counting'] : '')}`}
                onClick={toSendCaptcha}
            >
                { state.sending ? '发送中...' : '' }
                { state.counting ? `${state.time}s 后重试` : '' }
                { !state.sending && !state.counting ? '获取验证码' : '' }
            </div>
        </>
    )
});
